package com.jinglin.interceptor;

import com.alibaba.druid.support.json.JSONUtils;
import com.jinglin.common.UserThreadLocal;
import com.jinglin.pojo.User;
import com.jinglin.utils.JwtUtil;
import com.jinglin.utils.Result;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token  = request.getHeader("authorization");
        Claims claims = JwtUtil.parseJWT("jinglin", token);
        String username = (String) claims.get("username");
        String password = (String) claims.get("password");
        if ( username != null) {
            // 如果能从用户中拿到数据，则返回true，放行
            System.out.println("用户验证通过，当前用户："+ username);
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            UserThreadLocal.set(user);
            return true;
        } else {
            // Token 无效，返回错误信息
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为401
            // 构建返回的结果对象
            // 将结果对象转为 JSON 字符串
            Result<Object> result = new Result<>(1, "身份验证失败！！");
            System.out.println("身份验证失败！！！");
            String s = JSONUtils.toJSONString(result);
            response.getWriter().write(s);
            response.getWriter().flush();

            return false; // 阻止请求继续处理
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
